#include <QApplication>
#include <QDate>
#include <QDebug>
#include <QDialog>
#include <QDir>
#include <QFileInfo>
#include <QIcon>
#include <QLabel>
#include <QVBoxLayout>

#include "ButtonBeep.h"
#include "common/SerialPortLogger.h"
#include "global.h"
#include "mainwindow.h"
#include "sql/database.h"
#include "sql/errorlog.h"
#include "sql/upload_database.h"
#include "sql/user_database.h"

#define DATABASE_NAME "database.db"
// ANSI color codes
#define ANSI_COLOR_RESET "\x1b[0m"
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"

void setupLogging()
{
    // 确保log目录存在
    QDir logDir;
    if (!logDir.exists("log")) {
        if (logDir.mkpath("log")) {
            qDebug() << "Created log directory";
        } else {
            qWarning() << "Failed to create log directory";
            return;  // 如果创建目录失败，不安装日志处理器
        }
    }

    qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& context,
                              const QString& msg) {
        QString typeStr;
        const char* color = "";
        switch (type) {
            case QtDebugMsg:
                typeStr = "DEBUG";
                color = ANSI_COLOR_CYAN;
                break;
            case QtInfoMsg:
                typeStr = "INFO";
                color = ANSI_COLOR_GREEN;
                break;
            case QtWarningMsg:
                typeStr = "WARN";
                color = ANSI_COLOR_YELLOW;
                break;
            case QtCriticalMsg:
                typeStr = "ERROR";
                color = ANSI_COLOR_RED;
                break;
            case QtFatalMsg:
                typeStr = "FATAL";
                color = ANSI_COLOR_MAGENTA;
                break;
        }
        const char* file = context.file;
        QString filename = QFileInfo(file).baseName();  // 去除路径和后缀
        QString logMsg = QString("%1 【%2】 [%3:%4]  %5")
                             .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"))
                             .arg(typeStr, -5)      // 左对齐，最小宽度5
                             .arg(filename, -20)    // 左对齐，最小宽度20
                             .arg(context.line, 3)  // 右对齐，最小宽度3
                             .arg(msg);

        // 输出到控制台
#ifdef QT_DEBUG
        fprintf(stderr, "%s%s%s\n", color, logMsg.toLocal8Bit().constData(), ANSI_COLOR_RESET);
#else
        // 保存到日志文件（按年月/日存储）
        QDate currentDate = QDate::currentDate();
        QString yearMonth = currentDate.toString("yyyy-MM");
        QString day = currentDate.toString("dd");
        QString logPath = QString("log/%1/%2/StdStation.log").arg(yearMonth).arg(day);

        static QString currentLogPath;
        static QFile logFile;

        // 如果日期变化了，需要切换日志文件
        if (currentLogPath != logPath) {
            if (logFile.isOpen()) {
                logFile.close();
            }

            // 确保日期目录存在
            QFileInfo fileInfo(logPath);
            QDir logDir = fileInfo.absoluteDir();
            if (!logDir.exists()) {
                logDir.mkpath(".");
            }

            currentLogPath = logPath;
            logFile.setFileName(logPath);
        }

        if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
            QTextStream(&logFile) << logMsg << Qt::endl;
            logFile.close();
        }
#endif
    });
}

void setupLoadingDialog(QDialog* loading)
{
    loading->setWindowTitle("StdStation");
    loading->setWindowFlags(Qt::FramelessWindowHint |
                            Qt::WindowStaysOnTopHint);  // 去掉边框，保持在顶层
    loading->setFixedSize(600, 400);                    // 更大的尺寸

    // 设置窗口背景和圆角
    loading->setAttribute(Qt::WA_TranslucentBackground);  // 启用透明背景
    QVBoxLayout* layout = new QVBoxLayout(loading);

    // 添加图标
    QLabel* iconLabel = new QLabel(loading);
    QPixmap icon(":/icons/resource/icon/logo.svg");
    if (!icon.isNull()) {
        icon = icon.scaled(128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        iconLabel->setPixmap(icon);
    } else {
        iconLabel->setText("📱");
        iconLabel->setStyleSheet("font-size: 48px;");
    }
    iconLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(iconLabel);

    // 文字标签
    QLabel* label = new QLabel("正在加载窗口...", loading);
    label->setAlignment(Qt::AlignCenter);
    label->setStyleSheet(
        "font-size: 48px; "
        "font-weight: bold; "
        "color: #51a0ff; "
        "margin: 10px;");
    layout->addWidget(label);
}

void initializeDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(DATABASE_NAME);

    if (!db.open()) {
        qWarning() << "数据库连接失败";
        return;
    }
    Database::initTable();              // 初始化数据库
    UserDatabase::initUserTable();      // 初始化用户数据库
    UploadDatabase::initUploadTable();  // 初始化上传记录表
    ErrorLog::initTable();              // 初始化错误记录表
}
int main(int argc, char* argv[])
{
    QApplication a(argc, argv);

    // 显示加载窗口提示
    QDialog loading;
    setupLoadingDialog(&loading);
    loading.show();
    QCoreApplication::processEvents();

    // 设置应用程序图标
    a.setWindowIcon(QIcon(":/icons/resource/icon/logo.svg"));

    setupLogging();  // 设置日志
    qDebug() << "软件开始启动...[版本:" << APP_VERSION << "]";
    initializeDatabase();  // 初始化数据库

    // 初始化串口日志
    SerialPortLogger::instance().initialize();
    SerialPortLogger::instance().startLogging();
    MainWindow w;
    loading.close();
    w.show();
    enableAllButtonBeep();
    return a.exec();
}
